<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FaenterpriseController extends Controller
{

    /**
     * 企业认证列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','=',$param['me_uid']];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_nick_name']) && !empty($param['me_nick_name'])) {
            $whehe[] = ['b.me_nick_name','like',"%{$param['me_nick_name']}%"];
        }
        if (isset($param['enterprise_name']) && !empty($param['enterprise_name'])) {
            $whehe[] = ['a.enterprise_name','like',"%{$param['enterprise_name']}%"];
        }
        if (isset($param['enterprise_status']) && $param['enterprise_status'] != '') {
            $whehe[] = ['a.enterprise_status','=',$param['enterprise_status']];
        }

        $data = Db::table('fa_enterprise')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->where($whehe)
            ->field('a.*,b.member_id,b.me_uid,b.me_phone,b.me_nick_name')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $data->each(function ($v, $k) {
            switch($v['enterprise_status']){
                case '0': $v['enterprise_status_word'] = '待审核';break;
                case '1': $v['enterprise_status_word'] = '已通过';break;
                case '2': $v['enterprise_status_word'] = '已拒绝';break;
            }
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['refuse_time'] = !empty($v['refuse_time'])?date('Y-m-d H:i:s',$v['refuse_time']):'未审核';
            $v['phone'] = empty($v['enterprise_phone_two'])?$v['enterprise_phone']:$v['enterprise_phone'].' / '.$v['enterprise_phone_two'];
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }


    /**
     * 通过企业认证 页面
     * User:@hang
     */
    public function passenterprise($id)
    {
        //查询认证详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_enterprise',"`id` = '{$id}'",'*');
        $info['phone'] = empty($info['enterprise_phone_two'])?$info['enterprise_phone']:$info['enterprise_phone'].' / '.$info['enterprise_phone_two'];
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$info['member_id']}'",'member_id,me_uid,me_phone,me_nick_name');
        $this->assign([
            'data' => $id,
            'info' => $info,
            'memberinfo' => $memberInfo
        ]);
        return $this->fetch();
    }

    /**
     * 确认通过企业认证
     * User:@hang
     */
    public function actionpassenterprise()
    {
        $id = input('id');
        $refuse_content = input('refuse_content');
        if(empty($refuse_content)){
            return admin_error('请填写通过认证备注',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_enterprise',"`id` = '{$id}'",'*');
        if(empty($info)){
            return admin_error('企业认证信息未查询到',URL_CLOSE_REFRESH);
        }
        if($info['enterprise_status'] != 0){
            return admin_error('企业认证信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionpassenterprise'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_enterprise',"`id` = '{$id}'",array('enterprise_status'=>1,'user_id'=>$this->uid,'refuse_time'=>$ctime,'refuse_content'=>$refuse_content));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改企业认证信息失败',URL_CLOSE_REFRESH);
        }
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$info['member_id']}'",array('me_is_enterprise'=>1));
        $newsRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>7,'member_id'=>0,'j_member_id'=>$info['member_id'],'g_table'=>'fa_enterprise','g_id'=>$id,'content'=>'恭喜，您的企业认证已经通过，企业名称【'.$info['enterprise_name'].'】，认证通过时间：'.date('Y-m-d H:i:s',$ctime).'。','is_read'=>0,'add_time'=>$ctime));
        if(empty($newsRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户服务通知失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('通过企业认证成功',URL_CLOSE_REFRESH);
    }


    /**
     * 拒绝企业认证  页面
     * User:@hang
     */
    public function refuseenterprise($id)
    {
        //查询认证详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_enterprise',"`id` = '{$id}'",'*');
        $info['phone'] = empty($info['enterprise_phone_two'])?$info['enterprise_phone']:$info['enterprise_phone'].' / '.$info['enterprise_phone_two'];
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$info['member_id']}'",'member_id,me_uid,me_phone,me_nick_name');
        $this->assign([
            'data' => $id,
            'info' => $info,
            'memberinfo' => $memberInfo
        ]);
        return $this->fetch();
    }



    /**
     * 确认拒绝企业认证
     * User:@hang
     */
    public function actionrefuseenterprise()
    {
        $id = input('id');
        $refuse_content = input('refuse_content');
        if(empty($refuse_content)){
            return admin_error('请填写拒绝认证理由',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_enterprise',"`id` = '{$id}'",'*');
        if(empty($info)){
            return admin_error('企业认证信息未查询到',URL_CLOSE_REFRESH);
        }
        if($info['enterprise_status'] != 0){
            return admin_error('企业认证信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionrefuseenterprise'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_enterprise',"`id` = '{$id}'",array('enterprise_status'=>2,'user_id'=>$this->uid,'refuse_time'=>$ctime,'refuse_content'=>$refuse_content));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改企业认证信息失败',URL_CLOSE_REFRESH);
        }
        $newsRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>8,'member_id'=>0,'j_member_id'=>$info['member_id'],'g_table'=>'fa_enterprise','g_id'=>$id,'content'=>'抱歉，您的企业认证申请被拒绝，请前往修改并重新提交，企业名称【'.$info['enterprise_name'].'】，拒绝理由为【'.$refuse_content.'】，拒绝通过时间：'.date('Y-m-d H:i:s',$ctime).'。','is_read'=>0,'add_time'=>$ctime));
        if(empty($newsRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户服务通知失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('拒绝通过企业认证成功',URL_CLOSE_REFRESH);
    }



}
